import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { Button, Card, Col, Empty, Form, Row } from 'antd';
import { QuickForm } from 'vv-frontend-components';
import cn from 'classnames';
// import { history } from 'umi';
import QueryPage from '@/components/QueryPage';
import Locale from '@/utils/locale';
import styles from '@/pages/Attendance/Stat/Report/index.less';
import List from '@/components/List';
import TabsList from '@/components/List/TabsList';
// import request from '@/utils/request';
import updateQuery from '@/utils/formValuesToQuery';
import DateRange from '@/components/DateRange';
import { formatSecond } from '@/utils/utils';
// import Ygbmfb from '@/pages/Organization/Hr/zzjgComponents/Ygbmfb';
// import withClearState from '@/utils/withClearState';
import { withRoutePage } from '@/utils/enhanceUtils';
import { history } from 'umi';

import OrganizationSelect from '@/components/OrganizationSelect';
import CompanySort from './components/CompanySort';
import Type from './components/Type';
import Time from './components/Time';
import Status from './components/Status';
import Person from './components/Person';

const { locale } = new Locale('flow.manage.stat');

const lcsprphColumns = index => [
    {
        title: '序号',
        key: 'sort',
        render(text, record, i) {
            return (
                <span
                    className={cn(styles.xh, {
                        [styles.orange]: i <= 2
                    })}
                >
                    {i + 1}
                </span>
            );
        }
    },
    {
        title: 'employeeName',
        dataIndex: 'employeeName',
        key: 'employeeName'
    },
    {
        title: '次数',
        dataIndex: 'number',
        key: 'number',
        render(text, record) {
            if (index === 0) {
                return `${text} 次`;
            }
            if (index === 1) {
                return `平均审批时间${formatSecond(Number(record.avgTime / 1000 / 60), true, true)}`;
            }
            if (index === 2) {
                return `平均审批时间${formatSecond(Number(record.avgTime / 1000 / 60), true, true)}`;
            }
            return text;
        }
    }
];

const sqfqrphColumns = [
    {
        title: '序号',
        key: 'sort',
        render(text, record, index) {
            return (
                <span
                    className={cn(styles.xh, {
                        [styles.orange]: index <= 2
                    })}
                >
                    {index + 1}
                </span>
            );
        }
    },
    {
        title: 'employeeName',
        dataIndex: 'employeeName',
        key: 'employeeName'
    },
    {
        title: '次数',
        dataIndex: 'totalApplyCount',
        key: 'totalApplyCount',
        render(text) {
            return `${text} 次`;
        }
    }
];

const cylcphColumns = [
    {
        title: '序号',
        key: 'sort',
        render(text, record, index) {
            return (
                <span
                    className={cn(styles.xh, {
                        [styles.orange]: index <= 2
                    })}
                >
                    {index + 1}
                </span>
            );
        }
    },
    {
        title: '流程名称',
        dataIndex: 'name',
        key: 'name'
    },
    {
        title: '次数',
        dataIndex: 'count',
        key: 'count',
        render(text) {
            return `${text} 次`;
        }
    },
    {
        title: '发起人数',
        dataIndex: 'humanCount',
        key: 'humanCount',
        render(text) {
            return `${text} 人发起`;
        }
    }
];

const formatStartDate = date => {
    if (date) return moment(date);
    return moment()
        .subtract(1, 'M')
        .startOf('month');
};

const formatEndDate = date => {
    if (date) return moment(date);
    return moment()
        .subtract(1, 'M')
        .endOf('month');
};

const Stat = ({ form, stat, dispatch, loading, location, match }) => {
    // const { getFieldsValue } = form;
    const {
        query: { dateType, startTime, endTime }
    } = location;

    // const [sqfqrphIndex, setSqfqrphIndex] = useState(0);
    const sqfqrphIndex = 0;
    const [lcsprphIndex, setLcsprphIndex] = useState(0);
    // const [bmfbIndex, setBmfbIndex] = useState(0);
    const config = [
        {
            // 组织机构
            field: 'departmentCode',
            label: locale('xzzzjg'),
            config: {
                initialValue: location.query?.departmentCode
            },
            component: <OrganizationSelect isFunctional isNeedPermission style={{ width: 250 }} />
        },
        {
            // 行政机构
            field: 'companyCode',
            label: locale('xzxzjg'),
            config: {
                initialValue: location.query?.companyCode
            },
            component: <OrganizationSelect isNeedPermission style={{ width: 250 }} />
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [formatStartDate(startTime), formatEndDate(endTime)],
                    type: typeof dateType === 'undefined' ? 'month' : dateType
                }
            },
            component: <DateRange allowClear={false} />
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];

    // const changeIndex = index => setBmfbIndex(index);

    const goToRank = (tabName, restProps) => {
        const { departmentCode, companyCode, date = { range: [], type: '', quarter: 1 } } = form.getFieldsValue();

        return (
            <a
                onClick={() => {
                    history.push({
                        pathname: '/office/institutions/flowManage/stat/rank',
                        query: {
                            id: tabName,
                            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD 00:00:00') : '',
                            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD 23:59:59') : '',
                            dateType: date.type,
                            quarter: date?.type === 'quarter' ? date.quarter || 1 : '',
                            companyCode: companyCode || '',
                            departmentCode: departmentCode || ''
                        }
                    });
                }}
                {...restProps}
            >
                查看全部排行
            </a>
        );
    };

    const fetchData = async () => {
        const { departmentCode, companyCode, date = { range: [] } } = form.getFieldsValue();
        await dispatch({
            type: 'stat/fetchAllData',
            payload: {
                companyCode: companyCode || '',
                departmentCode: departmentCode || '',
                startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD 00:00:00') : '',
                endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD 23:59:59') : '',
                processType: sqfqrphIndex === 0 ? '' : sqfqrphIndex,
                processStatus: lcsprphIndex === 0 ? '' : lcsprphIndex
            }
        });
    };
    const handleSubmit = e => {
        const { departmentCode, companyCode, date } = form.getFieldsValue();
        e.preventDefault();
        fetchData();
        updateQuery(match.path, {
            companyCode: companyCode || '',
            departmentCode: departmentCode || '',
            dateType: date.type,
            startTime: date.range && date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD 00:00:00') : '',
            endTime: date.range && date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD 23:59:59') : ''
        });
    };

    const handleLcsprphChange = index => {
        setLcsprphIndex(+index);
        const { departmentCode, companyCode, date = { range: [] } } = form.getFieldsValue();
        dispatch({
            type: 'stat/fetchLcsprph',
            payload: {
                processStatus: +index === 0 ? '' : index,
                companyCode: companyCode || '',
                departmentCode: departmentCode || '',
                startTime: date.range[0] ? moment(date.range[0]).format('YYYY-MM-DD 00:00:00') : '',
                endTime: date.range[1] ? moment(date.range[1]).format('YYYY-MM-DD 23:59:59') : ''
            }
        });
    };

    const init = async () => {
        fetchData();
    };

    useEffect(() => {
        init();
        return () => {
            dispatch({
                type: 'stat/clear'
            });
        };
    }, []);
    return (
        <div className="reportPage">
            <QueryPage
                className="queryPageSearch"
                background="transparent"
                form={
                    <Row type="flex" className="searchTitle">
                        <Col>
                            <h3>{Locale.set('form.public.title')}</h3>
                        </Col>
                        <Col>
                            <Form layout="inline" onSubmit={handleSubmit}>
                                <QuickForm form={form} config={config} />
                            </Form>
                        </Col>
                    </Row>
                }
            />
            <div className={styles.cards}>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Person data={stat.sqspryfx} />
                    </Col>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.overflowY}
                            title={locale('sqfqrph')}
                            extra={goToRank('applicant')}
                        >
                            {stat.sqfqrph.length === 0 ? (
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            ) : (
                                <List data={stat.sqfqrph} columns={sqfqrphColumns} rowKey={row => row.id} />
                            )}
                        </Card>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Time data={stat.sphsfx} />
                    </Col>
                    <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                        {goToRank('approver', { className: styles.all })}
                        <TabsList
                            loading={loading.effects['stat/fetchLcsprph']}
                            activeKey={`${lcsprphIndex}`}
                            onTabChange={handleLcsprphChange}
                            title={locale('lcsprph')}
                            data={['审批达人', '审批快手', '审批慢手'].map((item, index) => ({
                                label: item,
                                content: (
                                    <List data={stat.lcsprph} columns={lcsprphColumns(index)} rowKey={row => row.id} />
                                )
                            }))}
                        />
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Type data={stat.spsqlxfx} />
                    </Col>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card
                            bordered={false}
                            className={styles.overflowY}
                            title={locale('cylcph')}
                            extra={goToRank('commonWorkflow')}
                        >
                            {stat.cylcph.length === 0 ? (
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            ) : (
                                <List
                                    loading={loading.effects['stat/fetchSqspryfx']}
                                    data={stat.cylcph}
                                    columns={cylcphColumns}
                                    rowKey={row => row.id}
                                />
                            )}
                        </Card>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Status data={stat.lcztfx} />
                    </Col>
                    <Col className={styles.relative} lg={{ span: 24 }} xl={{ span: 12 }}>
                        <Card bordered={false} className={styles.overflowY} title={locale('fqgsbmph')}>
                            <CompanySort
                                data={stat.fqgsbmph}
                                // changeIndex={changeIndex}
                                // selectedIndex={bmfbIndex}
                            />
                        </Card>
                    </Col>
                </Row>
            </div>
        </div>
    );
};

export default withRoutePage(connect(({ stat, loading }) => ({ stat, loading }))(Form.create()(Stat)));
